import { moonshotPost } from './request';

// Moonshot API 接口类型定义
export interface MoonshotMessage {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

export interface MoonshotChatRequest {
  model: string;
  messages: MoonshotMessage[];
  temperature?: number;
  max_tokens?: number;
  stream?: boolean;
}

export interface MoonshotChatResponse {
  id: string;
  object: string;
  created: number;
  model: string;
  choices: Array<{
    index: number;
    message: {
      role: string;
      content: string;
    };
    finish_reason: string;
  }>;
  usage: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
}

export interface MoonshotError {
  error: {
    message: string;
    type: string;
    code?: string;
  };
}

/**
 * Moonshot API 聊天完成接口
 * @param messages 消息数组
 * @param options 可选参数
 * @returns Promise<MoonshotChatResponse>
 */
export const chatCompletion = async (
  messages: MoonshotMessage[],
  options: {
    model?: string;
    temperature?: number;
    max_tokens?: number;
    stream?: boolean;
  } = {}
): Promise<MoonshotChatResponse> => {
  const {
    model = 'moonshot-v1-8k',
    temperature = 0.7,
    max_tokens = 1000,
    stream = false
  } = options;

  const requestData: MoonshotChatRequest = {
    model,
    messages,
    temperature,
    max_tokens,
    stream
  };

  try {
    const response = await moonshotPost('/chat/completions', requestData);
    return response.data;
  } catch (error: any) {
    console.error('Moonshot API 请求失败:', error);
    
    // 处理不同类型的错误
    if (error.response?.data) {
      const moonshotError = error.response.data as MoonshotError;
      const errorMessage = moonshotError.error.message;
      
      // 特殊处理API密钥错误
      if (errorMessage.includes('Incorrect API key') || errorMessage.includes('Invalid API key')) {
        throw new Error('API密钥无效或未设置。请检查 .env.local 文件中的 VITE_MOONSHOT_API_KEY 配置。');
      }
      
      throw new Error(`Moonshot API 错误: ${errorMessage}`);
    } else if (error.message) {
      throw new Error(`网络请求错误: ${error.message}`);
    } else {
      throw new Error('未知错误');
    }
  }
};

/**
 * 流式聊天完成接口
 * @param messages 消息数组
 * @param options 可选参数
 * @param onChunk 处理每个数据块的函数
 * @returns Promise<void>
 */
export const streamChatCompletion = async (
  messages: MoonshotMessage[],
  options: {
    model?: string;
    temperature?: number;
    max_tokens?: number;
  } = {},
  onChunk: (chunk: string) => void
): Promise<void> => {
  const {
    model = 'moonshot-v1-8k',
    temperature = 0.7,
    max_tokens = 1000
  } = options;

  const requestData: MoonshotChatRequest = {
    model,
    messages,
    temperature,
    max_tokens,
    stream: true
  };

  try {
    const response = await fetch('https://api.moonshot.cn/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${import.meta.env.VITE_MOONSHOT_API_KEY || ''}`
      },
      body: JSON.stringify(requestData)
    });

    if (!response.ok) {
      let errorMessage = '未知错误';
      try {
        const errorData = await response.json();
        errorMessage = errorData.error?.message || `HTTP ${response.status}`;
      } catch (parseError) {
        // 如果无法解析JSON，尝试读取文本
        try {
          const textError = await response.text();
          errorMessage = textError || `HTTP ${response.status}`;
        } catch (textError) {
          errorMessage = `HTTP ${response.status}`;
        }
      }
      throw new Error(`Moonshot API 错误: ${errorMessage}`);
    }

    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('无法读取响应流');
    }

    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      
      if (done) break;
      
      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(6);
          if (data === '[DONE]') {
            return;
          }
          
          try {
            const parsed = JSON.parse(data);
            const content = parsed.choices?.[0]?.delta?.content;
            if (content) {
              onChunk(content);
            }
          } catch (e) {
            console.warn('解析流数据失败:', e);
          }
        }
      }
    }
  } catch (error: any) {
    console.error('流式请求失败:', error);
    throw error;
  }
}; 